#include "HttpServer.hpp"
#include <memory>

using namespace server;
using namespace std;

static void Usage(string proc)
{
	std::cout << "\nUsage:\n\t" << proc << ": local_port\n\n";
}
// 1. 服务器和网页分离, html
// 2. url -> / : web 根目录
// 3. 根据特定的资源请求返回对应的后缀
std::string suffixToDesc(const std::string suffix)
{
	std::string ct = "Content-Type: ";
	if (suffix == ".html")
		ct += "text/html";
	else if (suffix == ".jpg")
		ct += "application/x-jpg";

	ct += "\r\n";
	return ct;
}
bool Get(const HttpRequest &req, HttpResponse &resp)
{
	cout << "----------------------------http start---------------------------------------" << endl;
	cout << req.inbuffer << endl;
	std::cout << "method: " << req.method << std::endl;
	std::cout << "url: " << req.url << std::endl;
	std::cout << "httpversion: " << req.httpversion << std::endl;
	std::cout << "path: " << req.path << std::endl;
	std::cout << "suffix: " << req.suffix << std::endl;
	std::cout << "size: " << req.size << "字节" << std::endl;
	cout << "-----------------------------http end--------------------------------------" << endl;
	
	std::string respline = "HTTP/1.1 200 OK\r\n";
	// std::string respline = "HTTP/1.1 307 Temporary Redirect\r\n";

	// std::string respheader = "Content-Type: text/html\r\n";
	std::string respheader = suffixToDesc(req.suffix);
	
	// if (req.size > 0)
	// {
	// 	respheader += "Content-Length: ";
	// 	respheader += std::to_string(req.size);
	// 	respheader += "\r\n";
	// }

	respheader += "Set-Cookie: name=123456abcd; Max-Age=120\r\n";
	// 往后, 每次http请求都会携带曾经的所有的Cookie

	// respheader += "Location: https://ys.mihoyo.com/main/\r\n";
	std::string respblank = "\r\n";

	std::string body;
	body.resize(req.size + 1);
	if (!Util::readFile(req.path, (char*)body.c_str(), req.size))
	{
		Util::readFile(html_404, (char*)body.c_str(), req.size); // 一定能成功
	}

	if (req.size > 0)
	{
		respheader += "Content-Length: ";
		respheader += std::to_string(body.size());
		respheader += "\r\n";
	}

	resp.outbuffer += respline;
	resp.outbuffer += respheader;
	resp.outbuffer += respblank;

	cout << "----------------------------http response start-------------------------------" << endl;
	std::cout << resp.outbuffer << std::endl;
	cout << "-----------------------------http response end--------------------------------" << endl;

	resp.outbuffer += body;
	return true;
}
int main(int argc, char *argv[])
{
	if (argc != 2)
	{
		Usage(argv[0]);
		exit(1);
	}

	uint16_t port = atoi(argv[1]);
	unique_ptr<HttpServer> httpsvr(new HttpServer(Get));
	// 功能路由
	// httpsvr->registerCb("/", Get);
	// httpsvr->registerCb("/search", Search);
	// httpsvr->registerCb("/test.py", Other);
	httpsvr->initServer();
	httpsvr->start();

	return 0;
}